package api

import (
	"batbat-backend/app/model"
	"batbat-backend/app/service"
	"batbat-backend/library/jwt"
	"batbat-backend/library/response"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

// Session 会话API接口, 主要管理用户的登录等内容
var Session = sessionApi{}

type sessionApi struct{}

// Login
// @summary 用户登录(需要加密)
// @tags 	会话
// @accept	mpfd
// @param	phoneNumber formData string true "手机号码"
// @param 	password formData string true "密码"
// @produce json
// @success 200 {object} response.JsonResponse{data=model.SessionApiLoginResp}
// @router 	/session [POST]
func (s *sessionApi) Login(r *ghttp.Request) {
	var req *model.SessionApiLoginReq
	err := service.Rsa.Decrypt(r, &req)
	if err != nil {
		response.Error(r, err)
	}
	user, err := service.Session.Login(r.Context(), req.PhoneNumber, req.Password)
	if err != nil {
		response.Error(r, err)
	}
	token, err := jwt.Generate(user)
	if err != nil {
		g.Log().Ctx(r.Context()).Errorf("生成jwt失败: %v", err)
		response.Error(r, gerror.New("登陆失败: 生成token失败"))
	}
	response.Success(r, &model.SessionApiLoginResp{
		User:  user,
		Token: token,
	})
}

// IsLogin
// @summary 判断用户是否登录
// @tags 	会话
// @param 	Authorization header string false "token"
// @produce json
// @success 200 {object} response.JsonResponse{data=bool}
// @router 	/session [GET]
func (s *sessionApi) IsLogin(r *ghttp.Request) {
	response.Success(r, !r.GetCtxVar(model.UserContextKey).IsNil())
}
